package com.dream.rpc.proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.dream.rpc.model.RpcRequest;
import com.dream.rpc.model.RpcResponse;
import com.dream.rpc.serializer.JdkSerializer;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 服务代理（jdk动态代理）
 * @author Dreamer
 */
public class ServiceProxy implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        JdkSerializer jdkSerializer = new JdkSerializer();

        //构造请求
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameterTypes(method.getParameterTypes())
                .args(args)
                .build();
        try {
            //序列化请求
            byte[] serialized = jdkSerializer.serialize(rpcRequest);
            //请求服务
            try(HttpResponse execute = HttpRequest.post("localhost:8080")
                    .body(serialized)
                    .execute();){
                byte[] result = execute.bodyBytes();
                //反序列化响应值
                RpcResponse deserialize = jdkSerializer.deserialize(result, RpcResponse.class);

                return deserialize.getData();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
